package com.vben.system.biz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vben.common.exception.enums.ErrorCode;
import com.vben.common.exception.system.user.UserException;
import com.vben.system.api.dto.role.SysRolePageDTO;
import com.vben.system.api.entity.SysRole;
import com.vben.system.biz.mapper.SysRoleMapper;
import com.vben.system.biz.service.SysRoleService;
import org.springframework.stereotype.Service;

/**
 * @author sunn
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public Page<SysRole> pageVO(SysRolePageDTO param) {
        String roleName = param.getRoleName();
        String roleCode = param.getRoleCode();

        Page<SysRole> page = param.buildMpPage();
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StrUtil.isNotBlank(roleName), SysRole::getRoleName, roleName);
        lambdaQueryWrapper.like(StrUtil.isNotBlank(roleCode), SysRole::getRoleCode, roleCode);
        return page(page, lambdaQueryWrapper);
    }

    @Override
    public SysRole getRoleById(Long roleId) {
        return getById(roleId);
    }

    @Override
    public Boolean saveRole(SysRole sysRole) {
        // 校验角色编码是否重复
        lambdaQuery()
                .eq(SysRole::getRoleCode, sysRole.getRoleCode())
                .ne(SysRole::getRoleId, sysRole.getRoleId())
                .oneOpt()
                .ifPresent(role -> {
                    throw new RuntimeException("角色编码已存在");
                });
        return save(sysRole);
    }

    @Override
    public Boolean updateRole(SysRole sysRole) {

        // 查询出现有角色
        SysRole oldRole = getById(sysRole.getRoleId());
        if (oldRole == null) {
            throw new UserException(ErrorCode.PARAM_INVALID, "角色不存在");
        }

        if (StrUtil.equals(oldRole.getRoleCode(), sysRole.getRoleCode())) {
            return updateById(sysRole);
        }
        // 校验角色编码是否重复
        lambdaQuery()
                .eq(SysRole::getRoleCode, sysRole.getRoleCode())
                .ne(SysRole::getRoleId, sysRole.getRoleId())
                .oneOpt()
                .ifPresent(role -> {
                    throw new RuntimeException("角色编码已存在");
                });
        return updateById(sysRole);
    }
}




